package com.ljh.account.Interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ljh.account.utils.Response;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class AdminInterceptor implements HandlerInterceptor{
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取当前请求的 Session
        HttpSession session = request.getSession(false); // 不创建新的 Session
        // 检查 Session 是否存在且是否是管理员
        if (session == null || session.getAttribute("accountType").equals("普通")) {
            // 如果不是管理员，禁止访问接口
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonResponse = objectMapper.writeValueAsString(Response.error("该用户无法访问后台接口！"));
            response.getWriter().write(jsonResponse);
            return false; // 拦截请求
        }



        return true; // 继续处理请求
    }
}
